#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

// 一直在写，不读 写阻塞
int main()
{
  int pipefd[2] = {0};
  if(pipe(pipefd) < 0){
    perror("pipe");
    return 1;
  }
  //printf("pipefd[0]:%d\n", pipefd[0]);//查看fd
  //printf("pipefd[0]:%d\n", pipefd[0]);
 
  pid_t id = fork();
  if(0 == id){//child, write
    close(pipefd[0]);//close  read 
    const char * msg = "I am child ...";
    int count  = 0;
    while(1){
      write(pipefd[1], msg, strlen(msg));
    }
    close(pipefd[1]);
    exit(0);
  }
  else{//parent, read 
    close(pipefd[1]);//close write 
    char buffer[64];
    int count = 0;
    while(1){
      ssize_t s = read(pipefd[0], buffer, sizeof(buffer)-1);//pipefd[0]读到buffer 第三个参数表示期望读取多少字节
      if(s > 0){
        buffer[s] = '\0';//buffer[s] = 0;最后一个结尾处为字符串结束
        printf("father get Message: %s\n", buffer);
      }
      count++;
      if(count > 5){
        close(pipefd[0]);//close read 
        break;
      }
      // // printf("father exit return : %d\n",s);
    }
  int status;
  pid_t ret = waitpid(id, &status, 0);
  if(ret > 0){
    printf("waitpid success! sig: %d exit code: %d\n", status&0xff, (status>>8)&0xff);
  }
    

  }//end of parent
  return 0;
}
